import axios from "axios"
import qs from "qs"
import store from '@/store'
import { Message } from "element-ui"
import router from "@/router"

// 设置默认请求头
axios.defaults.headers = {
  "Content-Type": "application/json;charset=UTF-8",
}
//设置axios请求超时时间
axios.defaults.timeout = 20 * 60 * 1000
//配置发送请求前的拦截器 可以设置token信息
axios.interceptors.request.use(
  (config) => {
    //设置JSON
    if (config.FORMDATE) {
      config.headers["Content-Type"] = "multipart/form-data;"
    } else if (config.FORM) {
      config.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8;"
    }
    //设置添加自定义的请求头
    if (store.state.user.token) config.headers.token = store.state.user.token
    if (store.state.user.userInfo) config.headers.user_id = store.state.user.userInfo.userId
    config.baseURL = process.env.NODE_ENV !== 'development' ? process.env.VUE_APP_BASE_URL : '/api'
    if (config.method == "post" || config.method == "POST") {
      if (config.FORM) {
        config.data = qs.stringify(config.data, {
          arrayFormat: "indices",
          allowDots: true,
        })
      }
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 配置响应拦截器
axios.interceptors.response.use(
  (res) => {
    //response响应判断
    // console.log('http res', res)
    let isExportFile = false
    let lastRequestUrlName = res.config.url.split('/').pop()
    // let specialArr = ['exportGoodsOrderExcel', 'importGoodsOrderExcel', 'exportPendingGoodsOrderExcel', 'exportMerInfo', 'exportMerStoreInfo']
    let requestUrl = res.config.url
    // 特殊接口处理（报表导出接口），不做统一拦截处理
    // if (requestUrl.includes('excel') || requestUrl.includes('getTemplate') || specialArr.includes(lastRequestUrlName)) isExportFile = true
    if (isExportFile) {
      return Promise.resolve(res.data)
    } else {
      if (res.data.code === 0 || res.data == '') {
        // console.log('http code 0', res)
        return Promise.resolve(res.data)
      } else {
        if (res.data.code == 401) {
          Message.error(res.data.msg || "登录失效,请重新登录");
          router.replace({
            path: "/login",
          })
        } else {
          Message.error(res.data.msg || "接口请求错误，请重新再试")
          return Promise.reject(res.data)
        }
        return Promise.reject(res.data)
      }
    }
  },
  (error) => {
    // console.log('http error', error)
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = "错误请求"
          break
        case 401:
          error.message = "未授权，请联系管理员"
          break
        case 404:
          error.message = "请求错误,未找到该资源"
          break
        case 405:
          error.message = "请求方式错误"
          break
        case 500:
          error.message = "服务器端出错"
          break
        default:
          error.message = `连接错误${error.response.status}`
      }
    } else {
      error.message = "连接到服务器失败"
    }
    Message.error(error.message)
    return Promise.reject(error.data)
  }
)

export default axios
